package ca.etsmtl.log320;

import java.util.concurrent.TimeUnit;

/**
 * Code pour l'interface de: http://stackoverflow.com/questions/3409099/building-a-gui-for-a-sudoku-solver-complete-with-ascii-example
 *
 * Simulates Sudoku solver. Demonstrates how to update GUI. The whole
 * implementation is constructed so GUI never freezes.
 */
class Log320SudokuImplementation implements SudokuImplementation {

	//initialised here so it doesn't take CPU time on the first time.
    boolean success;
    long startTime;
    long endTime;
    int[][] result;
    Backtracking backTrack;
    Optimised optimised;
    
    public Log320SudokuImplementation() {
        result = new int[9][9];
        backTrack = new Backtracking();
        optimised = new Optimised();
    }

    public void goButtonPressed(int[][] leftSudokuValues, SudokuController resultAcceptor) {
    	
    	//reset UI grid
        resultAcceptor.setSudokuCompleted(false);
    	resultAcceptor.setSudokuResult(leftSudokuValues);
    	
        success = false;
        startTime = 0;
        endTime = 0;

        //fill result grid with starting values
		for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
            	result[i][j] = leftSudokuValues[i][j];
            }
        }
				
		//start calculating
    	switch(resultAcceptor.getSolveMethod()) {
	    	case BackTracking: 
	    	{
		        //System.out.println("starting BACKTRACKING");
		        resultAcceptor.setSudokuTime("calcul en cours...");
		        startTime = System.nanoTime();

		        success = backTrack.calculateAnswer(/*leftSudokuValues,*/result);
		        		        		        
		        endTime = System.nanoTime();
		        break;	        
	    	}
	    	case Optimized:
	    	{
		        //System.out.println("starting OPTIMIZED");	
		        resultAcceptor.setSudokuTime("calcul en cours...");
		        startTime = System.nanoTime();

	        	success = optimised.calculateAnswer(result);
		        
		        endTime = System.nanoTime();	        
		        break;	  		
	    	}
    	}

    	//show results
    	String timeSpent = Long.toString((endTime - startTime)/1000);
    	if(timeSpent.length() > 3)
    		resultAcceptor.setSudokuTime( (new StringBuffer(timeSpent)).insert(timeSpent.length() - 3, ",").toString() + " ms");
    	else
    		resultAcceptor.setSudokuTime(timeSpent + " us");
    	
        if(success)
        	resultAcceptor.setSudokuResult(result);
        else
        	resultAcceptor.setSudokuResult(leftSudokuValues);
        
        resultAcceptor.setSudokuCompleted(success);
//        System.out.println("Done!");
    }
    
}